package com.lottery.football.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Spiders
{
	/**
	 * 抓取指定网页，编码为GB2312
	 * @param url
	 * @return
	 */
	public static String get(String url) 
	{
		return get(url, Constants.GB2312);
	}
	
	/**
	 * 以指定编码抓取网页
	 * @param url
	 * @param charset
	 * @return
	 */
	public static String get(String url, String charset)
	{
		try
		{
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpclient.execute(httpGet);
			try
			{
				System.out.println(response.getStatusLine());
				HttpEntity entity = response.getEntity();
				// do something useful with the response body
				// and ensure it is fully consumed
				// EntityUtils.consume(entity);
				if (entity != null)
				{
					// 获得响应的字符集编码信息
					// 即获取HTTP HEAD的：Content-Type:text/html;charset=UTF-8中的字符集信息
					//String charset = EntityUtils.getContentCharSet(entity);
					//ContentType contentType = ContentType.getOrDefault(entity);
					//Charset encoding = contentType.getCharset();
					
					InputStream is = entity.getContent();
					// IOUtils.copy(is, new FileOutputStream(""));

					
					return IOUtils.toString(is, charset);
				}
			}
			finally
			{
				response.close();
			}
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static String post(String url, Map<String, String> paramMap)
	{
		try
		{
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			
			// set parameters
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (paramMap != null && !paramMap.isEmpty())
			{
				Iterator<Map.Entry<String, String>> it = paramMap.entrySet().iterator();
				while(it.hasNext())
				{
					Map.Entry<String, String> entry = it.next();
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			CloseableHttpResponse response = httpclient.execute(httpPost);

			try
			{
				System.out.println(response.getStatusLine());
				HttpEntity entity = response.getEntity();
				// do something useful with the response body
				// and ensure it is fully consumed
				// EntityUtils.consume(entity2);
				if (entity != null)
				{
					// 获得响应的字符集编码信息
					// 即获取HTTP HEAD的：Content-Type:text/html;charset=UTF-8中的字符集信息
					String charset = EntityUtils.getContentCharSet(entity);
					InputStream is = entity.getContent();
					// IOUtils.copy(is, new FileOutputStream(""));

					return IOUtils.toString(is, charset);
				}
			}
			finally
			{
				response.close();
			}
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] getImage(HttpClient httpClient, String imageUrl)
	{
		try
		{
			// 利用HTTP GET向服务器发起请求
			HttpGet get = new HttpGet(imageUrl);
			// 获得服务器响应的的所有信息
			HttpResponse response = httpClient.execute(get);
			// 获得服务器响应回来的消息体（不包括HTTP HEAD）
			HttpEntity entity = response.getEntity();
			if (entity != null)
			{
				// 获得响应的字符集编码信息
				// 即获取HTTP HEAD的：Content-Type:text/html;charset=UTF-8中的字符集信息
				String charset = EntityUtils.getContentCharSet(entity);
				InputStream is = entity.getContent();
				return IOUtils.toByteArray(is);
			}
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static void shutdownClient(HttpClient client)
	{
		// 释放所有的链接资源，一般在所有的请求处理完成之后，才需要释放
		client.getConnectionManager().shutdown();
	}
}
